package com.matt.controller.api.web;

import com.dotflat.fin.utils.excelUtil.StringUtils;
import com.matt.commons.exception.BusinessException;
import com.matt.controller.po.ChildMemberPo;
import com.matt.domain.ClassReviewVo;
import com.matt.domain.Leads;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.PageResult;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.model.StatusResponse;
import com.matt.foundation.query.LeadsQuery;
import com.matt.foundation.query.StaffListQuery;
import com.matt.foundation.vo.ClienteleVo;
import com.matt.service.ClienteleService;
import com.matt.service.ContractService;
import com.matt.service.LeadsService;
import com.matt.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2018/6/13
 * *******************************
 */
@RestController
@RequestMapping("/web/leads")
@Api(tags = "CRM - 线索")
public class LeadsController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private LeadsService leadsService;

    @Autowired
    private ClienteleService clienteleService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private MemVerificationCache cache;


    /**
     * 添加线索
     *
     * @param ticket
     * @param leads
     * @return
     */
    @RequestMapping(value = "/add")
    public StatusResponse add(@RequestHeader String ticket, Leads leads) {
        return StatusResponse.success(leadsService.save(leads, ticket));
    }

    /**
     * 添加线索
     *
     * @param
     * @param leads
     * @return
     */
    @PostMapping(value = "/add1")
    public StatusResponse add1( @RequestBody Leads leads) {
        return StatusResponse.success(leadsService.save(leads, null));
    }

    /**
     * 查询所有园区
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/getAllArea")
    public StatusResponse getAllArea() {
        return StatusResponse.success(leadsService.getAllArea());
    }


    /**
     * 添加线索
     *
     * @param ticket
     * @param
     * @return
     */
    @PostMapping(value = "/add2")
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse add2(@RequestHeader String ticket,String name,String idCard,String mobile
            ,String areaId,String relationship) {
        Leads leads = new Leads();
        leads.setName(name);
        leads.setIdCard(idCard);
        leads.setMobile(mobile);
        leads.setAreaId(areaId);
        leads.setRelationship(relationship);
        return StatusResponse.success(leadsService.save1(leads, ticket));
    }


    /**
     * 修改线索
     *
     * @param ticket
     * @param leads
     * @return
     */
    @RequestMapping(value = "/updateById")
    public StatusResponse updateById(@RequestHeader String ticket, @RequestBody Leads leads) {
        return StatusResponse.success(leadsService.updateById(leads, ticket));
    }

    /**
     * 查询全部线索/我的线索(待跟进)
     *
     * @param leadsQuery
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/page")
    @ResponseBody
    public StatusResponse leadsByInfo(@RequestHeader String ticket, LeadsQuery leadsQuery, Pageable pageable) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        Page<Leads> page ;
        leadsQuery.setAreaId(staff.getAreaId());
        //判断是否有管理全部班级权限
        if ( ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_FULL }) ){
            page = leadsService.findPage(leadsQuery, pageable);
        }else if (ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_SALES })){
            leadsQuery.setStaffId(staff.getId());
            page = leadsService.findPage(leadsQuery, pageable);
        }else {
            page = new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
        return StatusResponse.success(page);
    }

    /**
     * 线索详情
     *
     * @param leadsId 线索id
     * @return
     */
    @RequestMapping(value = "/detail")
    public StatusResponse detail(@RequestHeader String ticket, String leadsId) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return StatusResponse.success(leadsService.findById(leadsId, staff.getAreaId()));
    }

    /**
     * 带有客户信息的线索详情
     * @param leadsId
     * @return
     */
    @RequestMapping(value = "/detail_with_clientele")
    public StatusResponse detailWithClientele(@RequestHeader String ticket, String leadsId) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        Leads leads = leadsService.findById(leadsId, staff.getAreaId());

        if(leads == null) {
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        ClienteleVo clientele = clienteleService.findByLeadsId(leads.getId());

        Map<String, Object> result = new HashMap();
        result.put("leads", leads);
        if(clientele != null) {
            result.put("clientele", clientele);
        }

        return StatusResponse.success(result);
    }

    /**
     * 删除线索
     *
     * @param leadsId
     * @return
     */
    @RequestMapping(value = "/delete")
    public StatusResponse delete(@RequestHeader String ticket, String leadsId) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return StatusResponse.success(leadsService.deleteByIdInArea(leadsId, ticket, staff.getAreaId()));
    }

    /**
     * 批量删除线索
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteAll")
    public StatusResponse delete(@RequestHeader String ticket, Leads leads) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return StatusResponse.success(leadsService.deleteByIdInArea1(leads.getLeadsId(), ticket, staff.getAreaId()));
    }

    /**
     * 获取员工信息
     *
     * @param ticket
     * @param staffId
     * @return
     */
    @RequestMapping(value = "/staffInfo")
    public StatusResponse findStaffInfo(@RequestHeader String ticket, String staffId) {
        return StatusResponse.success(ssoCallService.getStaffDTO(ticket, staffId));
    }

    /**
     * 修改线索负责人
     *
     * @param ticket
     * @param staffId 新负责人id
     * @param leadsId 线索id
     * @return
     */
    @RequestMapping(value = "/update_leads_staff")
    public StatusResponse updateLeadsStaffInfo(@RequestHeader String ticket, String staffId, String staffName, String leadsId) {
        try {
            return StatusResponse.success(leadsService.updateLeadsStaffInfo(ticket, staffId, staffName, leadsId));
        }catch (BusinessException e){
            if (StringUtils.equals(e.getErrorCode(), ErrorCode.LEADS_NOT_EXIST)){

                StaffDTO operator = ssoCallService.getStaffDTO(ticket);
                StaffDTO newStaff = ssoCallService.getStaffDTO(ticket, staffId);

                return StatusResponse.success(contractService.updateContractStaffInfo(operator, newStaff, leadsId));
            }

            throw e;
        }
    }

    /**
     * 批量修改线索负责人
     *
     * @param ticket
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/update_leads_staffs")
    public StatusResponse update_leads_staffs(@RequestHeader String ticket,Leads leads) {
        try {
            return StatusResponse.success(leadsService.updateLeadsStaffInfo1(ticket, leads.getStaffId(), leads.getStaffName()
                    , leads.getLeadsId()));
        }catch (BusinessException e){

            throw e;
        }
    }


    /**
     * 修改线索状态
     *
     * @param ticket
     * @param leadsId 线索id
     * @return
     */
    @RequestMapping(value = "/updateStatusById")
    public StatusResponse updateStatusById(@RequestHeader String ticket,String zhwysStatus, String leadsId) {
        return StatusResponse.success(leadsService.updateStatusById(ticket,zhwysStatus, leadsId));
    }

    /**
     * 成交
     *
     * @param ticket
     * @param po 线索id
     * @return
     */
    @RequestMapping(value = "/updateStatusByLeads")
    public StatusResponse updateStatusByLeads(@RequestHeader String ticket, ChildMemberPo po) {
        return StatusResponse.success(leadsService.updateStatusByLeads(ticket,po));
    }

    /**
     * 缴纳定金
     *
     * @param ticket
     * @param leads 线索id
     * @return
     */
    @RequestMapping(value = "/updatePennyById")
    public StatusResponse updatePennyById(@RequestHeader String ticket, Leads leads) {
        return StatusResponse.success(leadsService.updatePennyById(ticket,leads));
    }

    /**
     * 获取产品包
     *
     * @param ticket
     * @param
     * @return
     */
    @RequestMapping(value = "/selectProduct")
    public StatusResponse selectProduct(@RequestHeader String ticket) {
        return StatusResponse.success(ssoCallService.selectProduct(ticket));
    }

    /**
     * 获取课程评价记录
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/selectReview")
    public StatusResponse selectReview(@RequestHeader String ticket,String leadsId,Integer pageNum,Integer pageSize) {
        PageResult<ClassReviewVo> classReviewVoPageResult = ssoCallService.selectReview(leadsId, pageNum, pageSize, ticket);


        return StatusResponse.success(classReviewVoPageResult);
    }

    /**
     * 判断线索是否有跟进
     *
     * @param leadsId
     * @return
     */
    @RequestMapping(value = "/check_follow")
    public StatusResponse checkFollow(String leadsId) {
        return StatusResponse.success(leadsService.checkFollowById(leadsId));
    }

    @RequestMapping("/importLeadsExcel")
    public StatusResponse importLeadsExcel(@RequestHeader String ticket,  MultipartFile[] files){
        MultipartFile multipartFile = files[0];

        String errMsg = null;
        try {
            Map resultInfo = leadsService.importExcel(ticket,multipartFile);
            return StatusResponse.success(resultInfo);
        } catch (Exception e) {
            e.printStackTrace();
            errMsg = e.getLocalizedMessage();
            if(errMsg.length() == 0){
                errMsg = e.getMessage();
            }
        }

        return StatusResponse.error(ErrorCode.EXCEL_CHECK_ERROR, errMsg == null ? "模板处理失败" : ("Excel数据模板导入失败：" + errMsg));
    }
}
